//==========================================================================
// Copyright (c) 2000-2008,  Elastos, Inc.  All Rights Reserved.
//==========================================================================

#include <Windows.h>
#include <stdio.h>
#include "receive.h"
#include "DevicePower.h"

HANDLE hevent;
HANDLE hmmap;
HANDLE hmutex;
extern bool bExit;
void Receive_Initialize()
{
    for (int i = 0;!bExit && i < 100;i++) {
        hevent=OpenEvent(EVENT_ALL_ACCESS,FALSE,TEXT("DENTANCE_EVENT"));
        hmmap=OpenFileMapping(FILE_MAP_READ|FILE_MAP_WRITE,FALSE,TEXT("DENTANCE_NEWMODE"));
        hmutex=OpenMutex(MUTEX_ALL_ACCESS,FALSE,TEXT("DENTANCE_MUTEX"));
        if (hevent == NULL || hmmap == NULL || hmutex == NULL) {
            printf("kernal object:event or file map are not crated,waiting..........\n");
            Sleep(1000);
        }
        else
            break;
    }
    if (hevent == NULL || hmmap == NULL) {
        printf("kernal object:event or file map are not crated,quiting..........\n");
        exit(1);
    }
}

unsigned int Receive(unsigned * fre, float * vol)
{
    WaitForSingleObject(hevent,1000);
    unsigned int * pmap=(unsigned int *)MapViewOfFile(hmmap,FILE_MAP_READ|FILE_MAP_WRITE,0,0,0);
    *fre=*pmap;
    *vol=*((float*)(++pmap));
    return 0;
}

unsigned int ReceiveEx(void *pBuffer)
{//directly use the shared memory,not copy it,i think it is a safe way.
    WaitForSingleObject(hevent,1000);
    DWORD dw=WaitForSingleObject(hmutex,INFINITE);
    //printf("------------------------------receive info----------------------\n");
    if (dw == WAIT_OBJECT_0) {
        void * pmap=MapViewOfFile(hmmap,FILE_MAP_READ|FILE_MAP_WRITE,0,0,0);
        memcpy(pBuffer,pmap,MaxDevice*sizeof(Device_Power));//copy 320 byte
        ReleaseMutex(hmutex);
    }
    return 0;
}
void sleep(unsigned int time)
{
    Sleep(time);
}
